﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.API.Application.Common.Permission;
using RedDragon.RBAC.ErrorCodeEnum;
using T.Common.Domain.Common;
using Yitter.IdGenerator;

namespace RedDragon.RBAC.API.Application.Common.Client
{
    public class UpdateClientHandler: IRequestHandler<UpdateClientCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 权限仓储
        /// </summary>
        public readonly IBaseRepository<Clients> ClientRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdateClientHandler> logger;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="ClientRepository"></param>
        /// <param name="logger"></param>
        public UpdateClientHandler(IMapper mapper, IBaseRepository<Clients> ClientRepository, ILogger<UpdateClientHandler> logger)
        {
            this.mapper = mapper;
            this.ClientRepository = ClientRepository;
            this.logger = logger;
        }

        public async Task<Result> Handle(UpdateClientCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Clients Clients = mapper.Map<Clients>(request);
                //权限编号 雪花ID
                Clients.ClientsNo = YitIdHelper.NextId().ToString();
                var res = await ClientRepository.Update(Clients);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "客户修改成功";
                }

            }
            catch (Exception ex)
            {
                result.Msg = "客户修改失败" + ex.Message;
                logger.LogError("客户修改失败" + ex.Message);
            }
            return result;

        }

       

    }
}
